﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Activities;
using System.Activities.Statements;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WFDataBaseProject
{
    public class ConnectionScopeSequence:NativeActivity
    {
        public Collection<Activity> Activities { get; set; }
        [Category("Global variables")]
        [Description("The global connection going to be used by the childs activities")]
        public IDbConnection Connection { get; set; }
        public ConnectionScopeSequence()
        {
            Activities = new Collection<Activity>();
        }
        int activityCounter = 0;
        protected override void CacheMetadata(NativeActivityMetadata metadata) 
        {
               foreach (var activity in Activities)
               {
                   metadata.AddImplementationChild(activity);
               }
        }
        protected override void Execute(NativeActivityContext context)
        {
           ScheduleActivities(context);
        }
        void ScheduleActivities(NativeActivityContext context) {
        if (activityCounter < Activities.Count)
        context.ScheduleActivity(this.
        Activities[activityCounter++],
        OnActivityCompleted);
        }
        void OnActivityCompleted(NativeActivityContext context,ActivityInstance completedInstance) 
        {
            ScheduleActivities(context);
        }

        protected override void Abort(NativeActivityAbortContext context)
        {
            base.Abort(context);
            if (Connection!=null)
            {
                Connection.Close();
            }
        }
        protected override void Cancel(NativeActivityContext context)
        {
            base.Cancel(context);
            if (Connection!=null)
            {
                Connection.Close();
            }
        
        }
    }
}
